package com.kfm.springboot.controller;

import com.github.pagehelper.PageInfo;
import com.kfm.springboot.domain.Userinfo;
import com.kfm.springboot.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserinfoService service;

    @GetMapping
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView("user/index");
        return modelAndView;
    }

    @GetMapping("/list")
    public PageInfo<Userinfo> list(@RequestParam(value = "page", defaultValue = "1") int page
            , @RequestParam(value = "limit", defaultValue = "5") int limit, Userinfo userinfo) {
        return service.findAll(page, limit, userinfo);
    }

    @GetMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable(value = "id", required = false) String id){
        ModelAndView modelAndView = new ModelAndView("user/edit");
        modelAndView.addObject("user", service.findById(id));
        return modelAndView;
    }

    @GetMapping("/add")
    public ModelAndView add(){
        return new ModelAndView("user/edit");
    }

    @PostMapping("/edit")
    public String editUser(@RequestBody Userinfo userinfo){
        int row = -1;
        if (userinfo.getId() == null || "".equals(userinfo.getId())){
            // 新增
            row = service.add(userinfo);

        }else{
            // 修改
            row = service.modify(userinfo);
        }
        if (row > 0){
            return "success";
        } else {
            return "fail";
        }
    }

}
